<template>
	<view class="timetable">
		<!-- 美化后的头部 -->
		<view class="timetable-header">
			<view class="week-switch">
				<view class="action" @click="lastWeek">
					<text class="cuIcon-back"></text>
					<text class="text-bold">上一周</text>
				</view>
				<view class="week-picker" @click="weekOpen">
					第{{nowWeek+1}}周
					<uni-icons type="bottom" size="15"></uni-icons>
				</view>
				<view class="action" @click="nextWeek">
					<text class="text-bold">下一周</text>
					<text class="cuIcon-right"></text>
				</view>
			</view>
			<view class="action-group">
				<view class="action-btn" @click="openSetting">
					<uni-icons type="gear" size="22"></uni-icons>
				</view>
				<view class="action-btn" @click="openImport">
					<uni-icons type="download" size="22"></uni-icons>
				</view>
			</view>
		</view>
		<view class="header-wrap">
			<view class="month">
				<text class="month-text">{{tMonth}}<br>月</text>
			</view>

			<view class="left-text">

				<view :class="weeky==(i)?'text-content-today':'text-content'" v-for="i in 7" :key="i">
					<text class="week-txt" @click="clickDay(i,(nowWeek+1))"
						:style="{ 'color': dMonth === dateDetailsLi[i-1] ? '#FFF' : 'unset', 'background-color': dMonth === dateDetailsLi[i-1] ? '#4070FF' : 'unset' }">{{ week[i-1]}}</text>
					<text class="date-txt"
						:style="{ 'color': dMonth === dateDetailsLi[i-1] ? '#FFF' : 'unset','background-color': dMonth === dateDetailsLi[i-1] ? '#4070FF' : 'unset' }">{{ dateLi[i-1]}}</text>
				</view>
			</view>
		</view>
		<u-line></u-line>
		<!-- 课件时段 -->
		<view class="main">
			<view class="row" v-for="(item,index) in timetableType" :key="index">
				<u-line dashed color="#E4E7ED"></u-line>
				<view class="time-item">
					<view class="index">{{ item["course_num"] }}</view>
					<view class="time">{{ item["course_beg"]+"\n"+item["course_end"] }}</view>
				</view>
				<u-line dashed color="#E4E7ED"></u-line>
			</view>

			<view class="course-container">
				<view class="week" v-for="(week, weekIndex) in courseData" :key="weekIndex">
					<view class="courseList" v-for="(course, courseIndex) in week" :key="courseIndex">
						<view v-if="course.length > 0">
							<view @click="handleCourseClick(course, weekIndex, courseIndex)"
								@longpress="longPressLesson(course, weekIndex, courseIndex)" class="course" :style="{
			            background: course.backgroundColor,
			            borderColor: course.borderColor,
			            color: course.borderColor,
			            flex: course.length // 关键修改：用flex比例分配高度
			          }">
								{{ course.name }}
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 底部弹出层 显示周数 -->
		<view>
			<uni-popup ref="popup" type="bottom">
				<view class="bottom">
					<h4>点击查看该周课表</h4>
					<view style="margin-left: 80upx; margin-bottom: 100upx">
						<ly-data-checkbox mode="tag" @change="selectWeek" v-model="weekCurrent"
							:localdata="weekNumberList"></ly-data-checkbox>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'Timetable',
		props: {
			controlWeek: { //控制显示第几周
				type: [Number, String],
				default: 1
			},
			weekTableNumber: { //控制底部弹出层显示多少周数值
				type: [Number, String],
				default: 1
			},
			weekTableState: { //点击第几周是 是否开启底部周表
				type: Boolean,
				default: () => {
					return false
				}
			},
			timetableType: {
				type: Array,
				default: () => {
					return [

					]
				}
			},
			week: {
				type: Array,
				default: () => {
					return ['一', '二', '三', '四', '五', '六', '日']
				}
			},
			timetables: {
				type: Array,
				default: () => {
					return [{
							index: '1',
							name: '08:00\n08:40'
						},
						{
							index: '2',
							name: '08:50\n09:30'
						},
						{
							index: '3',
							name: '09:40\n10:20'
						},
						{
							index: '4',
							name: '10:30\n11:10'
						},
						{
							index: '5',
							name: '11:20\n12:00'
						},
						{
							index: '6',
							name: '14:00\n14:40'
						},
						{
							index: '7',
							name: '15:50\n16:30'
						},
						{
							index: '8',
							name: '16:40\n17:20'
						},
						{
							index: '9',
							name: '17:30\n18:10'
						},
						{
							index: '10',
							name: '19:00\n19:40'
						},
						{
							index: '11',
							name: '20:50\n21:30'
						},
						{
							index: '12',
							name: '21:40\n22:20'
						}
					]
				}
			},
			palette: {
				type: Array,
				default: () => {
					return []
				}
			},
			startdDate: {
				type: String,
				default: () => {
					return ""
				}
			},
			weekButton: {
				type: Boolean,
				default: () => {
					return false
				}
			},
		},
		data() {
			return {
				//borderPalette: [...this.palette, '#fe9d9f', '#91dcfc', '#f4f1d4', '#b0efd3', '#def7f8', '#93f5e0', '#e3e8fb', '#edf3b0', '#bcfbfc', '#efe2f9', '#ffe4a0', '#c9edf1', '#b495e1', '#ffe4a0', '#edffec'],
				allPalette: [
				  ...this.palette,
				  '#e0a0a5', // 樱花粉 (原#f05261 → 更明亮的粉调)
				  '#8fb3d1', // 晴空蓝 (原#48a8e4 → 带灰调的浅蓝)
				  '#e5d4a2', // 阳光米黄 (原#ffd061 → 柔和的奶油黄)
				  '#9dccb1', // 薄荷绿 (原#52db9a → 清新的浅绿色)
				  '#a8d5d5', // 浅水蓝 (原#70d3e6 → 更通透的蓝绿色)
				  '#9dccb1', // 薄荷绿 (重复)
				  '#7d8cb5', // 薰衣草紫 (原#3f51b5 → 柔和的灰紫色)
				  '#e5d992', // 香草黄 (原#f3d147 → 柔和的浅黄色)
				  '#8fd1c1', // 海沫绿 (原#4adbc3 → 清新的蓝绿色)
				  '#8d8fb5', // 紫藤色 (原#673ab7 → 明亮的灰紫色)
				  '#e5b992', // 杏桃色 (原#ff9800 → 柔和的橘调)
				  '#a3d1d1', // 天空蓝 (原#76bfcd → 更明亮的蓝绿色)
				  '#8d8fb5', // 紫藤色 (重复)
				  '#e5b992', // 杏桃色 (重复)
				  '#a8cc9d'  // 嫩芽绿 (原#8bc34a → 清新的黄绿色)
				],
				nowWeek: 0, // 当前周数下标 
				weekCurrent: 1, //当前周数
				weeky: 1,
				weekvalue: "", //星期几
				//weekNumber:0,//一共的周数 
				weekNumberList: [], //周数集合
				//week: ['周一','周二','周三','周四','周五','周六','周日'],
				dateLi: [12, 13, 14, 15, 16, 17, 18, 2],
				dateDetailsLi: [], //具体时间组
				date: 29, //当前日
				datetAndMonth: "",
				barHeight: 30,
				dMonth: 0, //当前月份 格式：08/09
				tMonth: 0, //左上角月份
				tMonthweeky: 0, //周期里面的月份
				frontDate: 0, //当前时间前 共有几天是这一周的下标数
				afterDate: 0, //当前时间后 共有几天是这一周的下标数
			}
		},
		created() {
			//获取当前日期
			this.dMonth = this.getWeek(0, "", 1)
			//this.weekNumber=10;
			for (let i = 0; i < this.weekTableNumber; i++) {
				this.weekNumberList.push({
					text: i + 1,
					value: i + 1
				})
			}
			//开始周日期 如：2022-08-28 通过这个时间计算离当前时间是第几周
			//计算多少天
			this.nowWeek = this.controlWeek - 1
			var index = this.nowWeek * 7
			//得到多少天之后日期
			let data2 = this.getfun_date(index)
			//console.log("这是上第",this.nowWeek+1,"周",index,"天以后",)
			//得到 data2 这一周的日期
			this.GetTime(data2)
		},
		computed: {
			courseData() {
				// 为数据标记背景颜色的函数
				let paletteIndex = 0
				const getBackgroundColor = () => {
					const backgroundColor = this.allPalette[paletteIndex]
					paletteIndex++
					if (paletteIndex >= this.allPalette.length) {
						paletteIndex = 0
					}
					return backgroundColor
				}
				// 合并
				const listMerge = []
				this.timetables.forEach(function(list, i) {
					if (!listMerge[i]) {
						listMerge[i] = []
					}
					list.forEach(function(item, index) {
						if (!item) item = {}
						if (!index) {
							return listMerge[i].push({
								name: item["course_name"],
								...item,
								length: 1,
								backgroundColor: !item["course_name"] ? 'none' :
									getBackgroundColor()
							})
						}
						if (item["course_name"] === (listMerge[i][index - 1] || {}).name && item[
								"course_name"]) {
							const sameIndex = (listMerge[i][index - 1] || {}).sameIndex
							if (sameIndex || sameIndex === 0) {
								listMerge[i][sameIndex].length++
								return listMerge[i].push({
									name: item["course_name"],
									...item,
									length: 0,
									sameIndex: sameIndex
								})
							}
							listMerge[i][index - 1].length++
							return listMerge[i].push({
								name: item["course_name"],
								...item,
								length: 0,
								sameIndex: index - 1,
							})
						} else {
							return listMerge[i].push({
								name: item["course_name"],
								...item,
								length: 1,
								backgroundColor: !item["course_name"] ? 'none' :
									getBackgroundColor()
							})
						}
					})
				})
				return listMerge
			},
			todayWeekIndex() {
				let weekIndex = new Date().getDay() - 1
				if (weekIndex === -1) {
					weekIndex = 6
				}
				console.log(weekIndex)
				return weekIndex
			}
		},
		methods: {
			// 设置按钮点击
			openSetting() {
				uni.showToast({
					// title: '点击了设置按钮',
					icon: 'none'
				});
				// 实际可跳转设置页面，比如：
				uni.navigateTo({
					url: '/pages/settings/settings'
				});
			},
			// 导入按钮点击
			openImport() {
				uni.showToast({
					// title: '点击了导入按钮',
					icon: 'none'
				});
				uni.navigateTo({
					url: '/pages/import/import'
				});
			},
			handleCourseClick(course, weekIndex, courseIndex) {
				const data = {
					index: courseIndex + 1,
					length: course.length,
					week: this.week[weekIndex],
					weekIndex: weekIndex,
					name: course["name"],
					course_id: course["course_id"],
					cal_date: course["cal_date"],
					course_beg: course["course_beg"],
					course_end: course["course_end"],
					course_pla: course["course_pla"]
				}
				//console.log(`星期${data.week}; 第${data.index}节课; 课程名:${data.name}; 课节:${data.length}`)
				// console.log(data)
				this.$emit('courseClick', data);
			},
			//上一周
			lastWeek() {
				if (this.nowWeek == 0) {
					//console.log("已经是第一周了")
					uni.$u.toast('已经是第一周了')
					return
				}
				this.nowWeek -= 1
				var index = this.nowWeek * 7
				let data2 = this.getfun_date(index)
				//console.log("这是上第",this.nowWeek,"周",index,"以后")
				this.GetTime(data2)
				//子组件事件
				this.$emit('lastWeekClick', this.nowWeek + 1)
			},
			//下一周
			nextWeek() {
				this.nowWeek += 1
				var index = (this.nowWeek - 1) * 7
				let i = this.afterDate + 1 + index

				let data2 = this.getfun_date(i)
				// console.log("这是下第",this.nowWeek,"周",index,i ,"以后","时间是",data2)
				this.GetTime(data2)

				//子组件事件
				this.$emit('nextWeekClick', this.nowWeek + 1)
			},
			//点击第几周事件 （显示弹出层）
			weekOpen() {
				this.$emit('weekOpenClick')
				if (!this.weekTableState) {
					return
				}
				// 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
				this.$refs.popup.open()
			},
			//底部弹出层  选择周数事件
			selectWeek(e) {
				// console.log(JSON.stringify(e.detail.value))
				this.nowWeek = e.detail.value - 1
				var index = this.nowWeek * 7
				let data2 = this.getfun_date(index)
				//console.log("这是上第",this.nowWeek,"周",index,"天以后",)
				this.GetTime(data2)
				this.$refs.popup.close()
				this.$emit('weekSelectClick', e.detail.value)
			},
			//计算一周日期
			GetTime(dateValue) {
				let date;
				if (dateValue != "") {
					date = new Date(dateValue)
					this.weekvalue = 0
				} else {
					date = new Date();
					var day = date.getDay();
					var arr_week = new Array("日", "一", "二", "三", "四", "五", "六");
					this.weekvalue = arr_week[day]
				}
				let weekIndex = date.getDay();
				let index = 0;
				let data = [] //日
				let dateDetails = [] //详细日期
				//得到当前月份
				this.tMonth = date.getMonth() + 1;
				//得到当前日期以及之前的
				index = weekIndex
				if (weekIndex == 0) {
					index = 7
				}
				for (let i = index - 1; i >= 0; i--) {
					dateDetails.push(this.getWeek(-i, dateValue, 1))
					if (this.getWeek(-i, dateValue) == 1) {
						data.push(date.getMonth() + 1 + "月")
						this.tMonth = date.getMonth();
					} else {
						data.push(this.getWeek(-i, dateValue))
					}
					this.frontDate = i;
					//console.log("得到当前日期以及之前的",this.getWeek(-i,dateValue))
				}
				//当前日期之后的
				if (weekIndex != 0) {
					for (let i = 1; i <= 7 - weekIndex; i++) {
						dateDetails.push(this.getWeek(i, dateValue, 1))
						if (this.getWeek(i, dateValue) == 1) {
							data.push(date.getMonth() + 2 + "月")
							this.tMonth = date.getMonth() + 1;
						} else {
							data.push(this.getWeek(i, dateValue))
						}
						this.afterDate = i;
						//console.log("当前日期之后的",this.getWeek(-i,dateValue))
					}
				}

				//赋值 一周的日期
				this.dateDetailsLi = dateDetails;
				this.dateLi = data;
			},
			//根据传的时间返回单个年 月 日
			getWeek(day, dateValue, state) {
				let today;
				if (dateValue != "") {
					today = new Date(dateValue)
				} else {
					today = new Date();
				}
				//var today = new Date();
				var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
				today.setTime(targetday_milliseconds);
				var tYear = today.getFullYear();
				var tMonth = today.getMonth();
				var tDate = today.getDate();
				tMonth = tMonth + 1;
				tDate = tDate;
				if (state == 1) {
					return tMonth + "/" + tDate;
				} else if (state == 2) {
					return tYear + "/" + tMonth + "/" + tDate;
				} else {
					return tDate;
				}
				//return  tMonth + "/" + tDate;
			},
			//查看 当前时间之前或者之后第几天的时间
			getfun_date(num) {
				let date1;
				if (this.startdDate != "") {
					date1 = new Date(this.startdDate)
				} else {
					date1 = new Date();
				}
				//var date1 = new Date();
				//今天时间
				var time1 = date1.getFullYear() + "-" + (date1.getMonth() + 1) + "-" + date1.getDate()
				var date2 = new Date(date1);
				date2.setDate(date1.getDate() + num);
				//num是正数表示之后的时间，num负数表示之前的时间，0表示今天
				var time2 = date2.getFullYear() + "-" + (date2.getMonth() + 1) + "-" + date2.getDate();
				// console.log(time2,'当前日期');
				return time2;
			},
			//日期相加减得到天数
			getDateDays(date1) {
				let a1 = Date.parse(new Date(date1))
				let a2 = Date.parse(new Date())
				let day = parseInt((a2 - a1) / (1000 * 60 * 60 * 24))
				return day;
			},
			//长按课表事件
			longPressLesson(course, weekIndex, courseIndex) {
				this.$emit('longPressLesson', course);
			},
			//点击日
			clickDay(r, w) {
				this.$emit('getLessonDay', r, w);
			}

		},
		watch: {
			//nowWeek 为接收参数的名称
			nowWeek: {
				handler(item, index) {
					// console.log(item,index)
					this.weekCurrent = item + 1
				},
				deep: true // 深度监听父组件传过来对象变化
			}
		},


	}
</script>

<style scoped lang="scss">
	// 新增头部样式
	.timetable-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10rpx 20rpx;
		background: $timetable-header-bg;
		color: var(--neutral-white);
		border-radius: 12rpx 12rpx 0 0;
	}

	.week-switch {
		display: flex;
		align-items: center;
		gap: 30rpx;

		.action {
			display: flex;
			align-items: center;
			cursor: pointer;
			transition: all 0.3s;

			&:active {
				opacity: 0.8;
				transform: scale(0.95);
			}

			.cuIcon-back,
			.cuIcon-right {
				margin-right: 8rpx;
				font-size: 24rpx;
				color: var(--neutral-white); // 图标颜色使用全局变量
			}
		}

		.week-picker {
			display: flex;
			align-items: center;
			cursor: pointer;
			padding: 8rpx 16rpx;
			background: rgba(255, 255, 255, 0.2);
			border-radius: 8rpx;
			transition: all 0.3s;

			&:active {
				background: rgba(255, 255, 255, 0.3);
			}

			uni-icons {
				margin-left: 8rpx;
				font-size: 20rpx;
				color: var(--neutral-white); // 图标颜色使用全局变量
			}
		}
	}

	.action-group {
		display: flex;
		gap: 20rpx;

		.action-btn {
			cursor: pointer;
			padding: 10rpx;
			border-radius: 50%;
			background: rgba(255, 255, 255, 0.2);
			transition: all 0.3s;

			&:active {
				background: rgba(255, 255, 255, 0.3);
				transform: scale(0.9);
			}

			uni-icons {
				font-size: 24rpx;
				color: var(--neutral-white); // 图标颜色使用全局变量
			}
		}
	}

	.bottom {
		background-color: var(--neutral-white); // 底部弹出层背景使用全局变量
		padding: 15px 0px;

		h4 {
			text-align: center;
			padding-bottom: 10px;
			color: var(--neutral-dark); // 标题颜色使用全局变量
		}

		border-radius: 15px 15px 0px 0px;
	}

	// 上一周，下一周控件（原cu-bar样式不再使用，保留代码便于后续参考）
	.cu-bar {
		display: flex;
		position: relative;
		align-items: center;
		min-height: 70rpx;
		justify-content: space-between;
		margin: 0px 15px;
		font-weight: bold;
		justify-content: space-between;
	}

	// 内容区域
	.timetable {
		background: var(--neutral-white); // 课表背景使用全局变量
		border: 1px solid var(--neutral-light); // 边框颜色使用全局变量
		border-radius: 8rpx;
		overflow: hidden;

		.header-wrap {
			display: flex;
			align-items: center;
			justify-content: flex-start;
			width: 100%;
			height: 80rpx;
			padding: 0 10rpx;
			box-sizing: border-box;
		}

		.left-text {
			display: flex;
			flex: 1;
			justify-content: space-around;
		}

		.month-text {
			width: 30px;
			height: 100%;
			text-align: center;
			font-weight: bold;
			padding: 6px 0px;
			color: var(--neutral-dark); // 月份文字颜色使用全局变量
		}

		.month {
			width: 50rpx;
			flex-shrink: 0;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.week-txt {
			width: 80%;
			height: 60%;
			text-align: center;
			font-size: 16px;
			font-weight: bold;
			margin-top: 5px;
			border-radius: 16rpx 16rpx 0px 0px;
		}

		.date-txt {
			width: 80%;
			height: 40%;
			text-align: center;
			font-size: 14px;
			color: var(--uni-text-color-grey); // 日期文字颜色使用全局变量
			padding-bottom: 5px;
			border-radius: 0px 0px 16rpx 16rpx;
		}

		.text-content {
			height: 100%;
			flex: 1;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			margin: 0 3rpx;
			padding: 6rpx 0;
			max-width: 120rpx;
			min-width: 80rpx;
		}

		.text-content-today {
			height: 100%;
			flex: 1;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			margin: 0 3rpx;
			padding: 6rpx 0;
			max-width: 120rpx;
			min-width: 80rpx;
		}
	}

	.main {
		position: relative;
		margin-top: 2px;

		.row {
			height: 80px;
			position: relative;

			&:after {
				content: '';
				height: 0;
				width: 100%;
				position: absolute;
				bottom: 0;
				left: 0;
				border-bottom: 1rpx dashed var(--neutral-light); // 虚线边框使用全局变量
			}

			.time-item {
				height: 100%;
				width: 70rpx;
				text-align: center;
				background: var(--neutral-light); // 时间项背景使用全局变量

				.index {
					padding-bottom: 8rpx;
					padding-top: 16rpx;
					font-size: 18px;
					color: var(--neutral-dark); // 课程序号颜色使用全局变量
				}

				.time {
					font-size: 12px;
					color: var(--uni-text-color-grey); // 时间文字颜色使用全局变量
				}
			}
		}

		.course-container {
			position: absolute;
			top: 0;
			left: 75rpx;
			width: calc(100% - 75rpx);
			height: 100%;
			display: flex;
			justify-content: space-around;

			.week {
				flex: 1;
				min-width: 0;
				display: flex;
				flex-direction: column;

				.courseList {
					flex: 1;
					display: flex;
					flex-direction: column;
					min-height: 0;
					padding: 0 2rpx;

					.course {
						flex: 1;
						min-height: 0;
						overflow: hidden;
						text-overflow: ellipsis;
						display: -webkit-box;
						-webkit-line-clamp: 3;
						-webkit-box-orient: vertical;
						border-radius: 16rpx;
						border-width: 1px;
						border-style: solid;
						padding: 4rpx;
						margin: 1rpx 0;
						text-align: center;
						font-size: 16px;
						word-break: break-word;
						box-sizing: border-box;
					}
				}
			}
		}
	}
</style>